<template>
  <a-modal
    title="选择采集器配置"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-card :bordered="false">

      <a-table
        ref="table"
        size="middle"
        :columns="columns"
        :dataSource="collectorConfigList"
        :rowKey="(record) => record.code"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
      </a-table>

    </a-card>
  </a-modal>
</template>

<script>
  import { STable } from '@/components'
  import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'
  import { addConfig } from '@/api/modular/main/bizcollectorconfig/bizCollectorConfigManage'

  export default {
    components: {
      STable
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        columns: [ // 表头
          {
            title: '编码',
            dataIndex: 'code'
          },
          {
            title: '采集器类型',
            dataIndex: 'value'
          }
        ],
        collectorConfigList: [],
        gatewayId: 0
      }
    },
    methods: {
      add (record) {
        this.visible = true
        this.gatewayId = record
      },
      loadData () {
        sysDictTypeDropDown({ code: 'collector_type' }).then((res) => {
          this.collectorConfigList = res.data
        })
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      handleSubmit () {
        this.confirmLoading = true
        addConfig({ codes: this.selectedRows, gatewayId: this.gatewayId }).then(res => {
          this.confirmLoading = false
          if (res.success) {
            this.$message.success('新增成功')
            this.handleCancel()
            this.$emit('ok', { codes: this.selectedRows, gatewayId: this.gatewayId })
          } else {
            this.$message.info('新增失败：' + res.message)
          }
        }).finally((res) => {
          this.confirmLoading = false
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.selectedRowKeys = []
        this.selectedRows = []
        this.visible = false
      }
    },
    mounted () {
      this.loadData()
    }
  }
</script>
